#-*-coding:gbk -*-

import urllib
import urllib2
import time
import md5
 
from tornado.options import options
from tornado.escape import json_decode

class Taobao:
	_app_key = None
	_app_secret = None
    	_fields	= 'title,price'
    	_params = None
    	def __init__(self, method):
		self._app_key = '#' #options.taobao_app_key
		self._app_secret = '#' #options.taobao_app_secret
		self._params = dict(
			app_key = self._app_key,
			method = 'taobao.' + method,
			v      = '2.0',
			nick   = 'isnono',
			timestamp = time.strftime('%Y-%m-%d %X',time.localtime()),
			sign_method = 'md5',
			format = 'json')

    	def _sign(self, **kw):
		for k,v in kw.iteritems():
			self._params[k] = v
			
		if not self._params.get('fields'):
			self._params['fields'] = self._fields
		
		src = self._app_secret + ''.join(["%s%s" % (k, v) for k, v in sorted(self._params.items())]) + self._app_secret
		return md5.new(src).hexdigest().upper()
	def fetch(self, **kw):
		self._params['sign'] = self._sign(**kw)
		form_data = urllib.urlencode(self._params)
		urlopen = urllib2.urlopen('http://gw.api.taobao.com/router/rest',form_data)
		return json_decode(urlopen.read().encode("utf8"))
			
		